package com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.css.fxfzxczh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzxczh.common.utils.UpdateUtil;
import com.css.fxfzxczh.constants.YNEnum;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.entity.HouMonData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.entity.HouMonDataCheckVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.entity.HouMonDataVo;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.queryParams.HouMonDataQuaParams;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.repository.HouMonDataRepository;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.service.HouMonDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.houMonData.verify.HouMonExcelVerifyHandler;
import com.css.fxfzxczh.modules.disasterSituationDataManage.lifeline.entity.Lifeline;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.entity.SamPoiData;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.service.SamPoiDataService;
import com.css.fxfzxczh.modules.disasterSituationDataManage.samPoiData.vo.ResultVo;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.param.AuditNotice;
import com.css.fxfzxczh.modules.fieldWorkManage.noticeManage.service.NoticeService;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.entity.ReportPublicField;
import com.css.fxfzxczh.modules.lossReportManage.lossReportEscalation.repository.ReportPublicFieldRepository;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.entity.EarEveManage;
import com.css.fxfzxczh.modules.synthesizeInfoManage.earEveManage.service.EarEveManageService;
import com.css.fxfzxczh.util.*;
import com.css.fxfzxczh.web.PlatformSessionContext;
import com.css.fxfzxczh.zcpt.sys.entity.SUser;
import com.css.fxfzxczh.zcpt.sys.service.SUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.*;

@Slf4j
@Service
public class HouMonDataServiceImpl implements HouMonDataService {

    @Resource
    HouMonDataRepository houMonDataRepository;

    @Resource
    SUserService sUserService;

    @Resource
    AttachmentInfoService attachmentInfoService;

    @Resource
    SamPoiDataService samPoiDataService;

    @Resource
    NoticeService noticeService;

    @Autowired
    EarEveManageService earEveManageService;

    @Autowired
    HouMonExcelVerifyHandler houMonExcelVerifyHandler;

    @Autowired
    ReportPublicFieldRepository reportPublicFieldRepository;
    @Resource
    private RedisLockUtil redisLockUtil;


    @Override
    public Map<String, Object> getPage(HouMonDataQuaParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = houMonDataRepository.getPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public void save(HouMonData houMonData) {
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        houMonData.setCreateUserName(sUser.getUserName());
        houMonData.setId(UUIDGenerator.getUUID());
        houMonData.setCreateTime(new Date());
        houMonData.setCreateUser(userID);
        houMonData.setDelFlag(YNEnum.N.toString());
        //0未提交
        houMonData.setCheckStatus("0");
        /*SamPoiData byId = samPoiDataService.findById(houMonData.getSamplingPointId());
        houMonData.setSamplingPointName(byId.getSamplingPointName());*/
        houMonDataRepository.save(houMonData);
    }

    @Override
    public void exportExcel(HttpServletResponse response, HouMonDataQuaParams queParams) {
        List<HouMonData> list = houMonDataRepository.getHouMonDataList(queParams);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "房屋单体样本数据信息统计", "房屋单体样本数据信息", HouMonData.class, "房屋单体样本数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getHouMonCode(String eventCode) {

        String requestId = UUIDGenerator.getUUID();
        String code = "";
        Boolean isLocked = redisLockUtil.lock("redis_eventCode_lock_serialNum", requestId, 6L);
        if (isLocked){
            log.info("成功获取redis_eventCode_lock_serialNum锁");
            EarEveManage currentEvent = earEveManageService.getCurrentEvent();
            eventCode=currentEvent.getEventCode();

            StringBuilder houMonCode = new StringBuilder(eventCode+"FWDT");
            DecimalFormat decimalFormat=new DecimalFormat("000");
            String num="";

            String maxNum=houMonDataRepository.getMaxNum(houMonCode.toString());
            if(PlatformObjectUtils.isEmpty(maxNum)){
                int i = 1;
                num=decimalFormat.format(i);
            }else{
                String substring = maxNum.substring(maxNum.length()-3);
                num = decimalFormat.format(Integer.parseInt(substring) + 1);
            }
            redisLockUtil.releaseLock("redis_distributed_lock_serialNum", requestId);
            log.info("成功释放redis_distributed_lock_serialNum锁");
            code=houMonCode.append(num).toString();
        }else {
            log.info("获取redis_eventCode_lock_serialNum锁失败，进行休眠");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return code;
    }

    @Override
    public HouMonDataVo findById(String id) {
        HouMonData houMonData = houMonDataRepository.findById(id);
        HouMonDataVo houMonDataVo=new HouMonDataVo();
        UpdateUtil.copyNullProperties(houMonData, houMonDataVo);
        if (PlatformObjectUtils.isNotEmpty(houMonData.getEnclosurePhoto())){
            houMonDataVo.setEnclosurePhoto(attachmentInfoService.queryFile(houMonData.getEnclosurePhoto()));
        }
        if (PlatformObjectUtils.isNotEmpty(houMonData.getEnclosureVideo())){
            houMonDataVo.setEnclosureVideo(attachmentInfoService.queryFile(houMonData.getEnclosureVideo()));
        }
        if (PlatformObjectUtils.isNotEmpty(houMonData.getEnclosureAudio())){
            houMonDataVo.setEnclosureAudio(attachmentInfoService.queryFile(houMonData.getEnclosureAudio()));
        }
        if (PlatformObjectUtils.isNotEmpty(houMonData.getEnclosureAlbum())){
            houMonDataVo.setEnclosureAlbum(attachmentInfoService.queryFile(houMonData.getEnclosureAlbum()));
        }

        return houMonDataVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(List<HouMonData> list) {
        ArrayList<AuditNotice> AuditList = new ArrayList<>();
        String user = sUserService.getSUser(PlatformSessionContext.getUserID());
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        for(HouMonData houMonData:list){
            houMonDataRepository.check(houMonData.getId(),houMonData.getCheckStatus(),houMonData.getCheckOpinion());
            if("3".equals(houMonData.getCheckStatus())){
                AuditNotice auditNotice = getAuditNotice(houMonData, sUser);
                AuditList.add(auditNotice);
            }
        }
        if (list.size()>0) {
            String s = noticeService.auditNotice(AuditList);
        }
    }

    //转换实体
    public AuditNotice getAuditNotice(HouMonData houMonData, SUser sUser) {
        AuditNotice auditNotice = new AuditNotice();
        auditNotice.setXnmId(UUID.randomUUID().toString().replaceAll("-", ""));
        auditNotice.setDelFlag(YNEnum.N.toString());
        auditNotice.setCreateUser(sUser.getUserId());
        auditNotice.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        auditNotice.setXsemId(houMonData.getXsemId());
        //通知类型
        auditNotice.setNoticeType("1");
        //通知名称
        auditNotice.setNoticeName("【" + houMonData.getSampleCode() + "】的房屋单体样本调查数据审核未通过");
        //通知内容
        auditNotice.setNoticeContent("数据编号为【" + houMonData.getSampleCode() + "】的房屋单体样本调查数据审核未通过,未通过原因【" + houMonData.getCheckOpinion() + "】");
        //发起人
        auditNotice.setSponsor(sUser.getUserName());
        //通知时间
        auditNotice.setNoticeTime(auditNotice.getCreateTime());
        //通知范围
        auditNotice.setNoticeRange(houMonData.getCreateUserName());
        //被通知人id
        auditNotice.setBeNotified(houMonData.getCreateUser());
        return auditNotice;
    }

    @Override
    public void checkExportExcel(HttpServletResponse response, HouMonDataQuaParams queParams) {
        List<HouMonDataCheckVo> list = houMonDataRepository.getHouMonCheckDataList(queParams);
        if (list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "房屋单体样本数据信息统计", "房屋单体样本数据信息", HouMonDataCheckVo.class, "房屋单体样本数据信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(HouMonData houMonData) {
        houMonData.setUpdateTime(new Date());
        houMonData.setUpdateUser(PlatformSessionContext.getUserID());
        houMonDataRepository.update(houMonData);
    }

    @Override
    public List<HouMonData> getBySamplingPointId(String samplingPointId) {
        return houMonDataRepository.getBySamplingPointId(samplingPointId);
    }

    @Override
    public Map<String, Object> importExcel(MultipartFile file,String xsemId) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setImportFields(new String[]{"省","市","区(县)","详细地址","抽样点名称","房屋单体名称","经度","纬度","结构类型","破坏情况","建筑面积（平方米）","用途类型","是否为典型房屋","损失值（元）","室内外财产损失比例","是否为中高档装修","具体描述情况"});
        params.setNeedVerify(true);
        params.setVerifyHandler(houMonExcelVerifyHandler);//校验
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            EarEveManage currentEvent = earEveManageService.getCurrentEvent();//获取当前地震事件
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<HouMonData> result = ExcelImportUtil.importExcelMore(inputStream, HouMonData.class, params);
            List<HouMonData> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (HouMonData houMonData : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(houMonData.getRowNum() + 1).append("行： ").append(houMonData.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            List<HouMonData> resultData = result.getList();//解析excel
            for(HouMonData houMonData : resultData){
                String uuid = UUIDGenerator.getUUID();
                houMonData.setId(uuid);
                houMonData.setXsemId(xsemId);
                String houMonCode = getHouMonCode(currentEvent.getEventCode());
                houMonData.setSampleCode(houMonCode);
                List<SamPoiData> list=samPoiDataService.findBySamplingPointName(houMonData.getSamplingPointName(),xsemId);
                if(list.size()>0){
                    //如果查出多个取第一个
                    SamPoiData samPoiData = list.get(0);
                    //houMonData.setSamplingPointName(resultVo.getSamplingPointName());
                    houMonData.setSamplingPointId(samPoiData.getId());
                    houMonData.setCheckStatus("2");
                    houMonData.setDelFlag("0");
                    houMonData.setCreateUserName(userName);
                    houMonData.setCreateUser(userId);
                    houMonData.setCreateTime(new Date());
                    String longitude = houMonData.getLongitude().toString();
                    String latitude = houMonData.getLatitude().toString();
                    String geom = "POINT("+longitude+" "+latitude+")";
                    houMonData.setGeom(geom);
                    res = houMonDataRepository.save(houMonData);

                    //保存专门维护省市区县的表
                    ReportPublicField reportPublicField = new ReportPublicField();
                    reportPublicField.setXlrmId(uuid);
                    reportPublicField.setXsemId(xsemId);
                    reportPublicField.setProvince(houMonData.getProvince());
                    reportPublicField.setCity(houMonData.getCity());
                    reportPublicField.setCounty(houMonData.getArea());
                    reportPublicField.setCreateUser(userId);
                    reportPublicField.setDelFlag("0");
                    reportPublicFieldRepository.save(reportPublicField);
                }else{
                    StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                    errorMsg.append("<font size='4px' ><br>").append("第").append(houMonData.getRowNum() + 1).append("行： ").append("未匹配到对应抽样点").append("</font>");
                    map.put("res", res);
                    map.put("mess", errorMsg);
                    return map;
                }
            }
        }catch (Exception e) {
        e.printStackTrace();
    }
        map.put("res",res);
        return map;


    }

    @Override
    public void submit(String ids) {
        String[] split = ids.split(",");
        for(String id:split){
            houMonDataRepository.submit(id);
        }
    }

    @Override
    public void delete(String ids) {
        houMonDataRepository.delete(ids.split(","));
    }

    @Override
    public Map<String, Object> getAppPage(HouMonDataQuaParams queParams, int curPage, int pageSize) {
        Map<String, Object> page = houMonDataRepository.getAppPage(queParams, curPage, pageSize);
        return page;
    }

    @Override
    public String saveApp(HouMonData houMonData) {
        String userID = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userID);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        houMonData.setCreateUserName(sUser.getUserName());
        houMonData.setId(UUIDGenerator.getUUID());
        houMonData.setCreateTime(new Date());
        houMonData.setCreateUser(userID);
        houMonData.setDelFlag(YNEnum.N.toString());
        //0未提交
        houMonData.setCheckStatus("0");
        /*SamPoiData byId = samPoiDataService.findById(houMonData.getSamplingPointId());
        houMonData.setSamplingPointName(byId.getSamplingPointName());*/
        houMonDataRepository.save(houMonData);
        return houMonData.getId();
    }


}
